<?php
namespace addons\mall\model;

use think\Db;
use think\Model;
use addons\mall\model\Goods;
use app\common\model\mall\user\Favorite;

/**
 * 标签业务处理类
 */
class Tags extends Model{

    /**
     * 获取指定商品
     */
    public function listGoods($type,$cat_id = 0,$num,$cache = 0){
        $type = strtolower($type);
        if(strtolower($type)=='history'){
            return $this->historyByGoods($num);
        }elseif(strtolower($type)=='guess'){
            return $this->getGuessLike($cat_id,$num);
        }elseif(strtolower($type)=='score'){//评分最高
            return $this->getScoreTop($cat_id,$num);
        }elseif(strtolower($type)=='wish'){//关注最多
            return $this->getWishTop($cat_id,$num);
        }else{
            return $this->listByGoods($type,$cat_id,$num,$cache);
        }
    }

    /**
     * 猜你喜欢
     * @param cat_id:分类id
     * @param num:数据条数
     */
    public function getGuessLike($cat_id,$num,$goods_ids=[]){
        $module = request()->isMobile();
        if(!empty($goods_ids)){
            $ids = $goods_ids;
        }else{
            $ids = ($module)?cookie("wx_history_goods"):cookie("history_goods");
        }
        // 当前无浏览记录，取热销商品
        $where = [];
        $where['goodsstatus'] = 1;
        $where['status'] = ['in','sale,warn'];
        $where['id'] = ['in',$ids];
        $goods_group = Goods::where($where)
            ->group('goodscat_ids')
            ->column('goodscat_ids');
        $goods = Goods::field('id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,marketprice,specis,appraisenum,visitnum,hotis,recomis,newis,shop_id')
            ->where($where)
            ->where('goodscat_ids','in',$goods_group)
            ->limit(3*$num)
            ->select();
        if(empty($goods))return $this->listByGoods('hot',$cat_id,$num);

        // 从数组中随机取$num个单元
        shuffle($goods);
        $goods = array_slice($goods,0,$num);

        //处理关注
        if(cookie('uid')){
            $f = new Favorite;
            foreach($goods as $k=>$v){
                $goods[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $goods[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }
        return $goods;
    }
    /**
     * 浏览商品
     */
    public function historyByGoods($num){
        $hids = $ids = cookie("history_goods");
        if(empty($ids))return [];
        $where = [];
        $where['goodsstatus'] = 1;
        $where['g.status'] = ['in',['sale','warn']];
        $where['g.id'] = ['in',$ids];
        $orderBy = Db::raw('field(g.`id`,'.implode(',',$ids).')');
        $goods = Goods::alias('g')
            ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id')
            ->field('s.name,g.shop_id,g.id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,marketprice,specis,appraisenum,visitnum,bestis,hotis,newis,recomis')
            ->where($where)->limit($num)->order($orderBy)->select();
        $ids = [];
        foreach($goods as $key =>$v){
            if($v['specis']==1)$ids[] = $v['id'];
        }
        if(!empty($ids)){
            $specs = [];
            $rs = Db::name('mall_goods_salespec')
                ->where(['goods_id'=>['in',$ids]])
                ->order('id')->select();
            foreach ($rs as $key => $v){
                $specs[$v['goods_id']] = $v;
            }
            foreach($goods as $key =>$v){
                if(isset($specs[$v['id']]))
                    $goods[$key]['specs'] = $specs[$v['id']];
            }
        }
        //处理关注
        if(cookie('uid')){
            $f = new Favorite;
            foreach($goods as $k=>$v){
                $goods[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $goods[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }
        return $goods;
    }

    /**
     * 评分最高
     */
    public function getScoreTop($cat_id,$num){

        $where = [];
        $where['goodsstatus'] = 1;
        $where['status'] = ['in','sale,warn'];
        $goods_group = Goods::where($where)
            ->group('goodscat_ids')
            ->column('goodscat_ids');
        $goods =Goods::alias("g")
            ->join("__MALL_GOODS_RATY__ s","g.id=s.goods_id","RIGHT")
            ->field('id,g.shop_id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,marketprice,specis,appraisenum,visitnum,newis,s.totalraty')
            ->where($where)
            ->where('goodscat_ids','in',$goods_group)
            ->order("s.totalraty desc")
            ->limit($num)
            ->select();
        // 当前无浏览记录，取热销商品
        if(empty($goods))return $this->listByGoods('hot',$cat_id,$num);
        //处理关注
        if(cookie('uid')){
            $f = new Favorite;
            foreach($goods as $k=>$v){
                $goods[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $goods[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }

        return $goods;
    }

    /**
     * 关注最多
     */
    public function getWishTop($cat_id,$num){

        $where = [];
        $where['goodsstatus'] = 1;
        $where['g.status'] = ['in','sale,warn'];
        $goods_group = Goods::alias("g")
            ->where($where)
            ->group('goodscat_ids')
            ->column('goodscat_ids');
        $goods = Goods::alias("g")
            ->join("__MALL_USER_FAVORITE__ f","f.type='goods' and g.id=f.target","RIGHT")
            ->field('g.id,shop_id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,marketprice,specis,appraisenum,visitnum,newis,count(f.target) wishtop')
            ->where($where)
            ->where('goodscat_ids','in',$goods_group)
            ->group('f.target')
            ->order("wishtop desc")
            ->limit($num)->select();

        // 当前无浏览记录，取热销商品
        if(empty($goods)) return $this->listByGoods('hot',$cat_id,$num);

        //处理关注
        if(cookie('uid')){
            $f = new Favorite;
            foreach($goods as $k=>$v){
                $goods[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $goods[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }

        return $goods;
    }

    /**
     * 推荐商品
     */
    public function listByGoods($type,$cat_id,$num,$cache = 0){
        if(!in_array($type,[0,1,2,3]))return [];
        $cacheData = cache('TAG_GOODS_'.$type."_".$cat_id."_".$num);
        if($cacheData)return $cacheData;
        //检测是否有数据
        $types = ['recom'=>0,'new'=>3,'hot'=>1,'best'=>2];
        $where = [];
        $where['r.dataSrc'] = 0;
        $where['g.goodsstatus'] = 1;
        $where['g.status'] = ['in','sale,warn'];
        $goods=[];
        if($type!='visit'){
            $where['r.dataType'] = $types[$type];
            //if($cat_id) $where[] = ['EXP',Db::raw("FIND_IN_SET(" . $cat_id . ",g.goodscat_ids)")];
            $where["r.goodsCatId"] = $cat_id;
            $goods = Goods::alias('g')
                ->join('__MALL_GOODS_RECOMMEND__ r','g.id=r.dataId',"LEFT")
                ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id')
                ->field('g.goodstips,s.name,s.id,g.id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,
                    marketprice,specis,appraisenum,visitnum,recomis,newis,hotis')
                ->where($where)->order('r.weigh asc')->limit($num)->select();
        }
        //判断有没有设置，如果没有设置的话则获取实际的数据
        if(empty($goods)){
            $types = ['recom'=>'recomis','new'=>'newis','hot'=>'hotis','best'=>'bestis'];
            $order = ['recom'=>'salenum desc,id asc',
                'new'=>'saletime desc,id asc',
                'hot'=>'salenum desc,id asc',
                'best'=>'salenum desc,id asc',
                'visit'=>'visitnum desc'
            ];
            
            $where = [];
            $where['goodsstatus'] = 1;
            $where['g.status'] = ['in','sale,warn'];
            
            if($type!='visit')
                $where[$types[$type]] = 1;

                if($cat_id) $where[] = ['EXP',Db::raw("FIND_IN_SET(" . $cat_id . ",g.goodscat_ids)")];
                $goods = Goods::alias('g')
                    ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id')
                    ->field('g.goodstips,s.name,g.shop_id,g.id,goodsname,goodsimg,goodssn,goodsstock,salenum,shopprice,marketprice,specis,appraisenum,visitnum,recomis,newis,hotis')
                    ->where($where)->order($order[$type])->limit($num)->select();
        }
        $ids = [];
        foreach($goods as $key =>$v){
            if($v['specis']==1) $ids[] = $v['id'];
        }
        if(!empty($ids)){
            $specs = [];
            $rs = Db::name('mall_goods_salespec gs ')->where('goods_id','in',$ids)->order('id asc')->select();
            foreach ($rs as $key => $v){
                $specs[$v['goods_id']] = $v;
            }
            foreach($goods as $key =>$v){
                if(isset($specs[$v['id']]))
                    $goods[$key]['specs'] = $specs[$v['id']];
            }
        }

        //处理关注
        if(cookie('uid')){
            $f = new Favorite;
            foreach($goods as $k=>$v){
                $goods[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $goods[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }

        cache('TAG_GOODS_'.$type."_".$cat_id."_".$num,$goods,$cache);
        return $goods;
    }

    /**
     * 获取广告位置
     */
    public function listAds($positionCode,$num,$cache = 0){
        $cacheData = cache('TAG_ADS'.$positionCode);
        if($cacheData)return $cacheData;
        $today = date('Y-m-d');
        $rs = Db::name("mall_oper_ads")->alias('a')
            ->join('__MALL_OPER_ADPOSITIONS__ ap','a.Position_id= ap.id and ap.state=1','left')
            ->where("a.state=1 and ap.code='".$positionCode."' and startdate<= '$today' and enddate>='$today'")
            ->field('a.id,adname,adurl,subtitle,adfile,ap.width,ap.height,content')
            ->order('a.weigh')->limit($num)->select();
        if(count($rs)>0){
            foreach ($rs as $key => $v) {
                $rs[$key]['isOpen'] = false;
                if(stripos($v['adurl'],'http:')!== false || stripos($v['adurl'],'https:')!== false){
                    $rs[$key]['isOpen'] = true;
                }
            }
        }
        cache('TAG_ADS'.$positionCode,$rs,$cache);
        return $rs;
    }
    
    /**
     * 获取友情链接
     */
    public function listFriendlink($num,$cache = 0){
        $cacheData = cache('TAG_FRIENDLINK');
        if($cacheData)return $cacheData;
        $rs = Db::name("mall_oper_friendlink")->where(["status"=>"normal"])->order("weigh asc")->select();
        cache('TAG_FRIENDLINK',$rs,$cache);
        return $rs;
    }
    
    /**
     * 获取文章列表
     */
    public function listArticle($cat_id,$num,$cache = 0){
        $cacheData = cache('TAG_ARTICLES_'.$cat_id."_".$num);
        if($cacheData)return $cacheData;
        $rs = [];
        if($cat_id=='new'){
            $rs = $this->listByNewArticle($num,$cache);
        }else{
            $rs = $this->listByArticle($cat_id,$num,$cache);
        }
        cache('TAG_ARTICLES_'.$cat_id."_".$num,$rs,$cache);
        return $rs;
    }
    /**
     * 获取最新文章
     */
    public function listByNewArticle($num,$cache){
        $cacheData = cache('TAG_NEW_ARTICLES');
        if($cacheData)return $cacheData;
        $rs = Db::name('mall_oper_help')->alias('a')
            ->field('a.id,a.articleTitle,a.coverimg,a.visitorNum,a.likeNum,a.updatetime,a.cat_id')
            ->join('mall_oper_helpcat ac','a.cat_id=ac.id','inner')
            ->where('ac.type=0 and ac.pid<>1 and a.state=1 and ac.showis=1 and a.showis=1 and ac.state=1')
            ->order('a.weigh asc,a.createtime desc')->limit($num)->select();
        cache('TAG_NEW_ARTICLES',$rs,$cache);
        return $rs;
    }
    /**
     * 获取指定分类的文章
     */
    public function listByArticle($cat_id,$num,$cache){
        $where = [];
        $where['state'] = 1;
        $where['showis'] = 1;
        if(is_array($cat_id)){
            $where['cat_id'] = ['in',$cat_id];
        }else{
            $where['cat_id'] = $cat_id;
        }
        return Db::name('mall_oper_help')->where($where)
        ->field("id, cat_id, articleTitle,coverimg,visitorNum,likeNum,updatetime,cat_id")->order('createtime desc')->limit($num)->select();
    }

    /**
     * 获取分类下的品牌
     */
    public function listBrand($cat_id,$num,$cache = 0){
        $cacheData = cache('TAG_BRANDS_'.$cat_id);
        if($cacheData) return $cacheData;
        $where = [];
        $where['r.dataSrc'] = 2;
        $where['b.status'] = 'normal';
        $where['r.dataType'] = 0;
        $where['r.goodsCatId'] = $cat_id;
        $brands = Db::name('mall_goods_brand')->alias('b')
            ->join('__MALL_GOODS_RECOMMEND__ r','b.id=r.dataId')
            ->where($where)->field('b.id,b.brandImg,b.name,r.goodsCatId cat_id')
            ->order('b.weigh desc')->limit($num)->select();
        //为空的话就取分类关联的
        if(empty($brands)){
            if($cat_id>0)$where['gc.id'] = $cat_id;
            $brands = Db::name('mall_goods_cat')->alias('gc')
                ->join('__MALL_GOODS_CATBRAND__ gcb','gc.id=gcb.cat_id','inner')
                ->join('__MALL_GOODS_BRAND__ b','gcb.brand_id=b.id','inner')
                ->field('b.id,b.brandimg,b.name,gcb.cat_id')
                ->group('b.id,gcb.cat_id')
                ->where('gc.status="normal" and gc.showis=1')
                ->where('b.status', 'normal')
                ->order('b.weigh desc')->limit($num)->select();
        }
        $brands = $this->unique_multidim_array($brands,'id');
        cache('TAG_BRANDS_'.$cat_id,$brands,$cache);
        return $brands;
    }
    // 二位数组去重
    protected function unique_multidim_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();
        foreach($array as $val) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }
    
    /**
     * 获取分类下的店铺
     */
    public function listShop($cat_id,$num,$cache = 0){
        $cacheData = cache('TAG_SHOPS_'.$cat_id);
        if($cacheData)return $cacheData;
        $where = [];
        $where['r.dataSrc'] = 1;
        $where['b.status'] = 'normal';
        $where['b.state'] = 1;
        $where['r.dataType'] = 0;
        $where['r.goodsCatId'] = $cat_id;
        $shops = Db::name('mall_shop_shop')->alias('b')
            ->join('__MALL_GOODS_RECOMMEND__ r','b.id=r.dataId')
            ->where($where)->field('b.id,b.shopImg,b.name,r.goodsCatId cat_id')
            ->order('r.weigh','asc')->limit($num)->select();
        //推荐的店铺为空，就获取取分类关联的店铺
        if(empty($shops)){
            $shops = Db::name('mall_goods_cat')->alias('gc')
            ->join('__MALL_SHOP_SHOP__ b','gc.id in(b.goodscat_ids) and b.state=1 and b.status="normal"','inner')
            ->field('b.id,b.shopImg,b.name,gc.id cat_id')
            ->where('gc.status="normal" and gc.showis=1 and gc.id='.$cat_id)
            ->limit($num)
            ->select();
        }
        cache('TAG_SHOPS_'.$cat_id,$shops,$cache);
        return $shops;
    }
    
    /**
     * 获取订单列表
     */
    public function listOrder($type,$num,$cache,$fields = ''){
        if(!in_array($type,['user','shop']))return [];
        $ownId = (int)($type=='user')?cookie('uid'):cookie('shop_id');
        if($ownId==0)return [];
        if($fields=='')$fields = 'order_id,orderNo,createTime,status,payType,deliverType,userName,realTotalMoney';
        $data = cache('TAG_ORDER_'.$type."_".$ownId);
        if(!$data){
            $where = '';
            if($type=='user')$where = 'user_id='.$ownId;
            if($type=='shop')$where = 'shop_id='.$ownId;
            $db = Db::name('mall_order_order')->where($where)->limit($num)->order('createTime','desc');
            if($fields!='')$db->field($fields);
            $data =$db->select();
            if(!empty($data)){
                $ids = [];
                foreach ($data as $key => $v) {
                    $ids[] = $v['order_id'];
                }
                $goods = Db::name('mall_order_goods')->where('order_id in ('.implode(',',$ids).')')->order('id','asc')->select();
                $goodsMap = [];
                foreach($goods as $g){
                    $goodsMap[$g['order_id']][] = $g;
                }
                foreach ($data as $key => $v) {
                    $data[$key]['goods'] = $goodsMap[$v['order_id']];
                }
            }
            cache('TAG_ORDER_'.$type."_".$ownId,$data,$cache);
        }
        return $data;
    }

    /**
     * 获取高评分商品
     */
    public function listScore($cat_id,$num,$cache = 0){
        $cacheData = cache('TAG_SCORE_'.$cat_id);
        if($cacheData) return $cacheData;

        $where = [];
        $where['g.status'] = ['in',['sale','warn']];
        $where['ga.status'] = ['in',['good','best']];
        $where['serviceraty'] = ['>=',4];
        $where['goodsraty'] = ['>=',4];
        $where['timeraty'] = ['>=',4];
        if($cat_id>0)$where[] = ['EXP','FIND_IN_SET($cat_id, "g.goodscat_ids")'];
        $scores = Goods::alias('g')
            ->field('g.id,g.goodsimg,g.goodsname,g.shopprice,ga.content,u.username,u.nickname')
            ->join('__MALL_GOODS_APPRAISE__ ga','g.id=ga.goods_id','inner')
            ->join('__USER__ u','u.id=ga.user_id','inner')
            ->order('ga.createtime desc')
            ->where($where)->limit($num)->select();

        cache('TAG_SCORE_'.$cat_id,$scores,$cache);
        return $scores;
    }
    
}
